package org.jeecg.modules.demo.ch.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.ChDesignBomDetail;
import org.jeecg.modules.demo.ch.entity.ChDesignBomDetailExcel;
import org.jeecg.modules.demo.ch.entity.ChDesignBomMaster;
import org.jeecg.modules.demo.ch.service.IChDesignBomDetailService;
import org.jeecg.modules.demo.ch.service.IChDesignBomMasterService;
import org.jeecg.modules.demo.ch.service.IChDesignBomService;
import org.jeecg.modules.demo.ch.vo.ChDesignBomPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 模具设计BOM表
 * @Author: jeecg-boot
 * @Date:   2022-09-12
 * @Version: V1.0
 */
@Api(tags="模具设计BOM表")
@RestController
@RequestMapping("/ch/chDesignBom")
@Slf4j
public class ChDesignBomController extends JeecgController<ChDesignBomPage, IChDesignBomService> {
	@Autowired
	private IChDesignBomService chDesignBomService;

	 @Autowired
	 private IChDesignBomDetailService iChDesignBomDetailService;

	 @Autowired
	 private IChDesignBomMasterService iChDesignBomMasterService;


	/**
	 *  查询现有的版本集合
	 * @param
	 * @return
	 */
	@AutoLog(value = "模具设计BOM-查询现有的版本集合")
	@ApiOperation(value="模具设计BOM-查询现有的版本集合", notes="模具设计BOM-查询现有的版本集合")
	@GetMapping(value = "/queryVersions")
	public Result<List<String>> queryVersions(ChDesignBomDetail chDesignBomDetail) {
		String moldCode = chDesignBomDetail.getMoldCode();	//根据模具编号获取id
	//	moldCode="ch2022019D";
		if (!StringUtils.hasLength(moldCode)){
			return Result.error("传来的模具编码不能为空!");
		}

		LambdaQueryWrapper<ChDesignBomMaster> chDesignBomMasterLambdaQueryWrapper = new QueryWrapper<ChDesignBomMaster>().lambda();
		chDesignBomMasterLambdaQueryWrapper.eq(ChDesignBomMaster::getMoldCode,moldCode);
		ChDesignBomMaster one = iChDesignBomMasterService.getOne(chDesignBomMasterLambdaQueryWrapper);
		if (one == null){
			return Result.error("根据模具编号:"+moldCode+"未查询到数据!");
		}

		//从ChOrderBom查询数据列表
		String	chDesignBomMasterId =one.getId();

		//根据模具设计BOM主表id获取最新的版本
		QueryWrapper<ChDesignBomDetail> chDesignBomDetailQueryWrapper = new QueryWrapper<>();
		chDesignBomDetailQueryWrapper.select("DISTINCT version as version");
		chDesignBomDetailQueryWrapper.eq("ch_design_bom_master_id",chDesignBomMasterId);
		List<ChDesignBomDetail> list = iChDesignBomDetailService.list(chDesignBomDetailQueryWrapper);

		if (list == null || list.size() == 0){
			return Result.error("根据模具主表id:"+moldCode+"未查询到最新的版本数据!");
		}
		//封装版本
		ArrayList<String> arrayList = new ArrayList<>();
		for (ChDesignBomDetail chDesignBomDetail1 : list) {
			arrayList.add(CommonMst.ORDER_BOM.V+chDesignBomDetail1.getVersion());
		}
		return Result.ok(arrayList);
	}


	/**
	 * 分页列表查询
	 *     @TableField(exist = false)
	 * @param chDesignBomDetail
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "模具设计BOM表-分页列表查询")
	@ApiOperation(value="模具设计BOM表-分页列表查询", notes="模具设计BOM表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ChDesignBomDetail>> queryPageList(ChDesignBomDetail chDesignBomDetail,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		log.info("传过来的参数：chDesignBomDetail:{},pageNo:{},pageSize:{}",chDesignBomDetail,pageNo,pageSize);
		String moldCode = chDesignBomDetail.getMoldCode();	//根据模具编号获取id
	//	moldCode="ch2022019D";
		QueryWrapper<ChDesignBomMaster> chDesignBomMasterQueryWrapper = new QueryWrapper<>();
	//	chDesignBomMasterQueryWrapper.eq(StringUtils.hasLength(moldCode),"mold_code",moldCode);
		chDesignBomMasterQueryWrapper.eq("mold_code",moldCode);
		ChDesignBomMaster chDesignBomMaster = iChDesignBomMasterService.getOne(chDesignBomMasterQueryWrapper);
		if (chDesignBomMaster == null){
			return Result.error("根据模具编号:"+moldCode+"未查询到数据!");
		}
		String	chDesignBomMasterId =chDesignBomMaster.getId();

		//根据模具设计BOM主表id获取最新的版本
		QueryWrapper<ChDesignBomDetail> chDesignBomDetailQueryWrapper = new QueryWrapper<>();
		chDesignBomDetailQueryWrapper.select("MAX(version) as version");
		chDesignBomDetailQueryWrapper.eq("ch_design_bom_master_id",chDesignBomMasterId);
		ChDesignBomDetail bomServiceOne = iChDesignBomDetailService.getOne(chDesignBomDetailQueryWrapper);
		if (bomServiceOne == null){
			return Result.error("根据模具主表id:"+moldCode+"未查询到最新的版本数据!");
		}

	//	QueryWrapper<ChDesignBomDetail> queryWrapper = QueryGenerator.initQueryWrapper(chDesignBomDetail, req.getParameterMap());
		QueryWrapper<ChDesignBomDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("ch_design_bom_master_id",chDesignBomMasterId);//根据主表id查询附属表
		queryWrapper.eq("is_delete",0); //获取正常数据
		String material = chDesignBomDetail.getMaterial();//获取材料
		Integer transferBenefitModelStatus = chDesignBomDetail.getTransferBenefitModelStatus();//转益模的状态（1.未转2.已转）
		queryWrapper.eq(StringUtils.hasLength(material) && material.equals("STD"),"material",material);
		queryWrapper.ne(StringUtils.hasLength(material) && material.equals("非STD"),"material","STD");
		queryWrapper.eq(null != transferBenefitModelStatus ,"transfer_benefit_model_status",transferBenefitModelStatus);
		queryWrapper.orderByAsc("serial_number");
		Page<ChDesignBomDetail> page = new Page<>(pageNo, pageSize);
		IPage<ChDesignBomDetail> pageList = iChDesignBomDetailService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param chDesignBomPage
	 * @return
	 */
	@AutoLog(value = "模具设计BOM表-添加")
	@ApiOperation(value="模具设计BOM表-添加", notes="模具设计BOM表-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ChDesignBomPage chDesignBomPage) {
		chDesignBomService.save(chDesignBomPage);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param chDesignBomPage
	 * @return
	 */
	@AutoLog(value = "模具设计BOM表-编辑")
	@ApiOperation(value="模具设计BOM表-编辑", notes="模具设计BOM表-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ChDesignBomPage chDesignBomPage) {
		chDesignBomService.updateById(chDesignBomPage);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "模具设计BOM表-通过id删除")
	@ApiOperation(value="模具设计BOM表-通过id删除", notes="模具设计BOM表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		chDesignBomService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "模具设计BOM表-批量删除")
	@ApiOperation(value="模具设计BOM表-批量删除", notes="模具设计BOM表-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.chDesignBomService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "模具设计BOM表-通过id查询")
	@ApiOperation(value="模具设计BOM表-通过id查询", notes="模具设计BOM表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ChDesignBomPage> queryById(@RequestParam(name="id",required=true) String id) {
		ChDesignBomPage chDesignBomPage = chDesignBomService.getById(id);
		if(chDesignBomPage==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(chDesignBomPage);
	}


	 /**Ob
	  * 导出excel
	  *
	  * @param request
	  * @param chDesignBomDetail
	  */
	 //@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom:exportXls")
	 @RequestMapping(value = "/exportXls")  //exportXls
	 public void exportXls(HttpServletRequest request, HttpServletResponse response, ChDesignBomDetail chDesignBomDetail) {

		 try{

			 log.info("传过来的参数：chDesignBomDetail:{}", chDesignBomDetail);
			 // Step.1 组装查询条件查询数据
			 String moldCode = chDesignBomDetail.getMoldCode();    //根据模具编号获取id
			 QueryWrapper<ChDesignBomMaster> chDesignBomMasterQueryWrapper = new QueryWrapper<>();
			 chDesignBomMasterQueryWrapper.eq(StringUtils.hasLength(moldCode), "mold_code", moldCode);
			 List<ChDesignBomMaster> chDesignBomMasterListStr = iChDesignBomMasterService.list(chDesignBomMasterQueryWrapper);
			 if (chDesignBomMasterListStr.isEmpty() || chDesignBomMasterListStr.size()==0 ) {
				 return;
				// return Result.error("无数据导出!");
			 }

	//		 QueryWrapper<ChDesignBomDetail> queryWrapper = QueryGenerator.initQueryWrapper(chDesignBomDetail, request.getParameterMap());
			 QueryWrapper<ChDesignBomDetail> queryWrapper = new QueryWrapper<>();
			 queryWrapper.eq("ch_design_bom_master_id", chDesignBomMasterListStr.get(0).getId());//根据主表id查询附属表
			 String material = chDesignBomDetail.getMaterial();//获取材料
			 Integer transferBenefitModelStatus = chDesignBomDetail.getTransferBenefitModelStatus();//转益模的状态（1.未转2.已转）
			 queryWrapper.eq(StringUtils.hasLength(material) && material.equals("STD"),"material",material);
			 queryWrapper.ne(StringUtils.hasLength(material) && material.equals("非STD"),"material","STD");
			 queryWrapper.eq(null != transferBenefitModelStatus ,"transfer_benefit_model_status",transferBenefitModelStatus);
			 queryWrapper.orderByAsc("serial_number");

			 //	LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

			 //配置选中数据查询条件
			 String selections = request.getParameter("selections");
			 if (oConvertUtils.isNotEmpty(selections)) {
				 List<String> selectionList = Arrays.asList(selections.split(","));
				 queryWrapper.in("id", selectionList);
			 }
			 //Step.2 获取导出数据
			 List<ChDesignBomDetail> chDesignBomMasterList = iChDesignBomDetailService.list(queryWrapper);
			 log.info("需要导出的数据chDesignBomMasterList.size():{}",chDesignBomMasterList.size());
			 // Step.3 组装rows
			 ArrayList<ChDesignBomDetailExcel> rows = new ArrayList<>();

			 for (ChDesignBomDetail designBomDetail : chDesignBomMasterList) {
				 ChDesignBomDetailExcel chDesignBomDetailExcel = new ChDesignBomDetailExcel();
				 String serialNumber = designBomDetail.getSerialNumber() != null ? String.valueOf(designBomDetail.getSerialNumber()) : "";
				 chDesignBomDetailExcel.setSerialNumber(serialNumber);
				 String partName =designBomDetail.getPartName() != null ? String.valueOf(designBomDetail.getPartName()) : "";
				 chDesignBomDetailExcel.setPartName(partName);
				 String chineseName =designBomDetail.getChineseName() != null ? String.valueOf(designBomDetail.getChineseName()) : "";
				 chDesignBomDetailExcel.setChineseName(chineseName);
				 String number =designBomDetail.getNumber() != null ? String.valueOf(designBomDetail.getNumber()) : "";
				 chDesignBomDetailExcel.setNumber(number);
				 String englishName =designBomDetail.getEnglishName() != null ? String.valueOf(designBomDetail.getEnglishName()) : "";
				 chDesignBomDetailExcel.setEnglishName(englishName);
				 String partSpecification =designBomDetail.getPartSpecification() != null ? String.valueOf(designBomDetail.getPartSpecification()) : "";
				 chDesignBomDetailExcel.setPartSpecification(partSpecification);
				 String material2 =designBomDetail.getMaterial() != null ? String.valueOf(designBomDetail.getMaterial()) : "";
				 chDesignBomDetailExcel.setMaterial(material2);
				 String remark =designBomDetail.getRemark() != null ? String.valueOf(designBomDetail.getRemark()) : "";
				 chDesignBomDetailExcel.setRemark(remark);
				 rows.add(chDesignBomDetailExcel);
			 }

			 // 通过工具类创建writer
			// createFile(new File(templatePath));
			 ExcelWriter writer = ExcelUtil.getWriter(true);

			 //自定义标题别名
			 writer.addHeaderAlias("serialNumber", "序号");
			 writer.addHeaderAlias("partName", "零件名");
			 writer.addHeaderAlias("chineseName", "中文名");
			 writer.addHeaderAlias("number", "数量");
			 writer.addHeaderAlias("englishName", "英文名");
			 writer.addHeaderAlias("partSpecification", "零件规格");
			 writer.addHeaderAlias("material", "材料");
			 writer.addHeaderAlias("remark", "备注");

			// 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
			 writer.setOnlyAlias(true);

			 //跳过当前行，既第一行，非必须，在此演示用
			 writer.passCurrentRow();
			 writer.passCurrentRow();
			 writer.passCurrentRow();
			 // 合并单元格后的标题行，使用默认标题样式
			 writer.merge(7, "益模系统的BOM导入模版");
			 // 一次性写出内容，使用默认样式，强制输出标题
			 writer.write(rows, true);


			 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
			 response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
			 ServletOutputStream out=response.getOutputStream();
			 writer.flush(out, true);
			 writer.close();
			 IoUtil.close(out);

			 //修改状态.
			 for (ChDesignBomDetail designBomDetail : chDesignBomMasterList) {
				 designBomDetail.setTransferBenefitModelStatus(2);
			 }
			 iChDesignBomDetailService.updateBatchById(chDesignBomMasterList);
			 // return Result.ok("文件导出成功!存放的路径是:"+templatePath);
		 }catch (Exception e){
			 log.error("文件导出异常!",e);
			// return Result.error("文件导出异常!",e);
		 }
	 }





	 /**
	  * 判断文件是否存在，不存在就创建
	  * @param file
	  */
	 public static void createFile(File file) {
		 if (file.exists()) {
			 log.info("File exists:{}",file);
		 } else {
			 //getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
			 if (!file.getParentFile().exists()) {
				 //创建上级目录
				 file.getParentFile().mkdirs();
			 }
			 try {
				 //在上级目录里创建文件
				 file.createNewFile();
			 } catch (IOException e) {
				 e.printStackTrace();
			 }
		 }
	 }




//    /**Ob
//    * 导出excel
//    *
//    * @param request
//    * @param chDesignBomDetail
//    */
//    //@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom:exportXls")
//    @RequestMapping(value = "/exportXls")
//    public void exportXls(HttpServletRequest request, HttpServletRequest response, ChDesignBomDetail chDesignBomDetail) {
//
//		try{
//		//	String templatePath = "D:\\JAVA\\poi\\CHT-BOM.xlsx";  用这个对象XSSFWorkbook
//			String templatePath = "D:\\JAVA\\poi\\CHT-BOM.xlsx";
//
//
//			log.info("传过来的参数：chDesignBomDetail:{}", chDesignBomDetail);
//			// Step.1 组装查询条件查询数据
//			String moldCode = chDesignBomDetail.getMoldCode();    //根据模具编号获取id
//			QueryWrapper<ChDesignBomMaster> chDesignBomMasterQueryWrapper = new QueryWrapper<>();
//			chDesignBomMasterQueryWrapper.eq(StringUtils.hasLength(moldCode), "mold_code", moldCode);
//			List<ChDesignBomMaster> chDesignBomMasterListStr = iChDesignBomMasterService.list(chDesignBomMasterQueryWrapper);
//			if (chDesignBomMasterListStr.isEmpty() || chDesignBomMasterListStr.size()==0 ) {
//			//	return Result.error("无数据导出!");
//				return;
//			}
//
//			QueryWrapper<ChDesignBomDetail> queryWrapper = QueryGenerator.initQueryWrapper(chDesignBomDetail, request.getParameterMap());
//			queryWrapper.eq("ch_design_bom_master_id", chDesignBomMasterListStr.get(0).getId());//根据主表id查询附属表
//			String material = chDesignBomDetail.getMaterial();//获取材料
//			queryWrapper.eq(StringUtils.hasLength(material) && material.equals("SID"), "material", material);
//			queryWrapper.ne(StringUtils.hasLength(material) && material.equals("非SID"), "material", material);
//			queryWrapper.orderByAsc("serial_number");
//
//		//	LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//
//			//配置选中数据查询条件
//			String selections = request.getParameter("selections");
//			if (oConvertUtils.isNotEmpty(selections)) {
//				List<String> selectionList = Arrays.asList(selections.split(","));
//				queryWrapper.in("id", selectionList);
//			}
//			//Step.2 获取导出数据
//			List<ChDesignBomDetail> chDesignBomMasterList = iChDesignBomDetailService.list(queryWrapper);
//			log.info("需要导出的数据chDesignBomMasterList.size():{}",chDesignBomMasterList.size());
//			// Step.3 组装pageList
//
//			// Step.4 AutoPoi 导出Excel
//
//			//1.用servletContext对象获取excel模板的真实路径
////			FileInputStream inps = new FileInputStream(templatePath);
////			Workbook  wb	= WorkbookFactory.create(inps);  //直接用多态的形式会导致导不出文件内容
//
//			XSSFWorkbook wb = new XSSFWorkbook(templatePath);
//			//HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(templatePath)); //TODO:经过测试 导出无内容
//
//			//2.读取excel模板,创建excel对象
//
//			//3.读取sheet对象
//			Sheet sheet = wb.getSheetAt(0);
//			//4.定义一些可复用的对象
//			int rowIndex = 2; //行的索引
//			int cellIndex = 0; //单元格的索引
//			Row nRow = null;
//			Cell nCell = null;
//			//5.读取大标题行
//			nRow = sheet.getRow(rowIndex++); // 使用后 +1
//			//6.读取大标题的单元格
//			nCell = nRow.getCell(cellIndex);
//			//7.设置大标题的内容
//			nCell.setCellValue("");
//			//8.跳过第二行(模板的小标题,我们要用)
//			rowIndex++;
//			//9.读取第三行,获取它的样式
//			nRow = sheet.getRow(rowIndex);
//			//读取行高
//			float lineHeight = nRow.getHeightInPoints();
//			//10.获取第三行的5个单元格中的样式
//			CellStyle cs1 = nRow.getCell(cellIndex++).getCellStyle();
//			CellStyle cs2 = nRow.getCell(cellIndex++).getCellStyle();
//			CellStyle cs3 = nRow.getCell(cellIndex++).getCellStyle();
//			CellStyle cs4 = nRow.getCell(cellIndex++).getCellStyle();
//			CellStyle cs5 = nRow.getCell(cellIndex++).getCellStyle();
//			CellStyle cs6 = nRow.getCell(cellIndex++).getCellStyle();
//			CellStyle cs7 = nRow.getCell(cellIndex++).getCellStyle();
//			CellStyle cs8 = nRow.getCell(cellIndex++).getCellStyle();
//			//11.通过月份查询新增用户列表
//
//			//12.遍历数据
//			for (ChDesignBomDetail chDesignBom : chDesignBomMasterList) {
//				//13.创建数据行
//				nRow = sheet.createRow(++rowIndex);
//				//16.设置数据行高
//				nRow.setHeightInPoints(lineHeight);
//				//17.重置cellIndex,从第一列开始写数据
//				cellIndex = 0;
//				//18.创建数据单元格，设置单元格内容和样式
//				//序号
//				nCell = nRow.createCell(cellIndex++);
//				nCell.setCellStyle(cs1);
//				nCell.setCellValue(chDesignBom.getSerialNumber());
//				//零件名
//				nCell = nRow.createCell(cellIndex++);
//				nCell.setCellStyle(cs2);
//				nCell.setCellValue(chDesignBom.getPartName());
//				//中文名
//				nCell = nRow.createCell(cellIndex++);
//				nCell.setCellStyle(cs3);
//				nCell.setCellValue(chDesignBom.getChineseName());
//				//数量
//				nCell = nRow.createCell(cellIndex++);
//				nCell.setCellStyle(cs4);
//				nCell.setCellValue(chDesignBom.getNumber());
//				//英文名
//				nCell = nRow.createCell(cellIndex++);
//				nCell.setCellStyle(cs5);
//				nCell.setCellValue(chDesignBom.getEnglishName());
//				//零件规格
//				nCell = nRow.createCell(cellIndex++);
//				nCell.setCellStyle(cs6);
//				nCell.setCellValue(chDesignBom.getPartSpecification());
//				//材料
//				nCell = nRow.createCell(cellIndex++);
//				nCell.setCellStyle(cs7);
//				nCell.setCellValue(chDesignBom.getMaterial());
//				//备注
//				nCell = nRow.createCell(cellIndex++);
//				nCell.setCellStyle(cs8);
//				nCell.setCellValue(chDesignBom.getRemark());
//			}
//
//			//最后，下载新增用户表，字节数组的输出流，它可存可取，带缓冲区
//			ByteArrayOutputStream bos = new ByteArrayOutputStream();
//			wb.write(bos); //将工作簿写到输出流中
//			//new DownloadUtil().download(bos,response,bigTitle+".xlsx");
//			bos.close();
//			wb.close();
//		//	return Result.ok("文件导出成功!存放的路径是:"+templatePath);
//		}catch (Exception e){
//			log.error("文件导出异常!",e);
//		//	return Result.error("文件导出异常!",e);
//		}
//	}

//	 public static TemplateExportParams getTemplateParams(String name){
//		 return new TemplateExportParams("E:\\changhong\\software\\设计BOM\\"+name+".xls");
//	 }


    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("ch_design_bom:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ChDesignBomPage.class);
    }





	//获取配置文件中的端口
//    @Value("${server.port}")
	private String port="8080";
	//定义接口的ip
	private static final String ip = "http://localhost";

	/*
    上传接口
     */
	//MultipartFile用于接受前端传过来的file对象
	@PostMapping("/upload")
	public Result<?> upload(MultipartFile file) throws IOException {
		String filename = file.getOriginalFilename();//获取文件的名称

        /*
        我们需要给我们的文件加一个文件前缀，不可以加文件后缀，因为我们的文件还有后缀名
        加文件前缀的目的是为了防止文件重名，文件重名的话后续的重名文件会覆盖掉前面的文件
         */
		String flag = IdUtil.fastSimpleUUID();//通过Hutool工具包的IdUtil类获取uuid作为前缀
		String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + filename;
		FileUtil.writeBytes(file.getBytes(), rootFilePath);//使用Hutool工具包将我们接收到文件保存到rootFilePath中
		return Result.OK(ip + ":" + port + "/files/" + flag);//返回结果   ：  url，
	}


	/*
    下载接口
     */
	@GetMapping("/{flag}")
	public void getFiles(@PathVariable String flag, HttpServletResponse response) {
		OutputStream os;//新建一个输出流对象
		String basePath = System.getProperty("user.dir") + "/src/main/resources/files/"; //定义文件上传的根路径
		List<String> fileNames = FileUtil.listFileNames(basePath);//获取所有的文件名称
		String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到跟参数一致的文件
		try {
			if (StrUtil.isNotEmpty(fileName)) {
				response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
				response.setContentType("application/octet-stream");
				byte[] bytes = FileUtil.readBytes(basePath + fileName);//通过文件的路径读取文件字节流
				os = response.getOutputStream();//通过response的输出流返回文件
				os.write(bytes);
				os.flush();
				os.close();
			}
		} catch (Exception e) {
			System.out.println("文件下载失败");
		}

	}

}
